package com.zm.cinema.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zm.cinema.entity.User;
import com.zm.cinema.mapper.UserMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

@Component
@ServerEndpoint("/talk/{id}")
@Slf4j
public class TalkWebSocket {
    static HashSet<Session> sessions = new HashSet<>();

    @Autowired
    UserMapper userMapper;
    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id) throws IOException {
        log.info(id+" 上线了！");
        User user = userMapper.selectById(id);
        session.getUserProperties().put("user",user);
        sessions.add(session);
        send(new MsgInfo(sessions.stream()
                .map(s->(User)s.getUserProperties().get("user"))
                .collect(Collectors.toList()),
                user,
                " 上线了！"
        ));
    }

    @OnClose
    public void onClose(Session session){
        User user = (User) session.getUserProperties().get("user");
        log.info(user.getName()+" 下线了！");
        sessions.remove(user);
    }

    @OnMessage
    public void onMessage(Session session,String message) throws IOException {
        User user = (User) session.getUserProperties().get("user");
        log.info(user.getName()+" 说：" +message);
        send(new MsgInfo(null,user,message));
    }

    public void send(MsgInfo msgInfo) throws IOException {
        String message = new ObjectMapper().writeValueAsString(msgInfo);
        for (Session s : sessions) {
            s.getBasicRemote().sendText(message);
        }
    }
}

@Data
@NoArgsConstructor
@AllArgsConstructor
class MsgInfo{
    //在线用户列表
    private List<User> onlines;
    //发送人
    private User senUser;
    //文字消息
    private String message;

}
